import { Component, Input } from '@angular/core';
import { MenuService } from 'src/app/@core/services/menu/menu.service';
import Mmenu from '../../../../@core/data/MobilePermissions.json';
@Component({
  selector: 'app-mobile-permissions',
  templateUrl: './mobile-permissions.component.html',
  styleUrls: ['./mobile-permissions.component.scss']
})
export class MobilePermissionsComponent {
  @Input() data:any
  TreeData:any = [];
  displayData: any[] = [];
  searchDirctoryValue:any=''
  selectTitle:any=[]
  selectMenus: any[];
  selectIds: any[];
  constructor(private MenuService:MenuService) { }
  ngOnInit(): void {
    this.MenuService.GetAllAppMenus().subscribe((data: any) => {
      this.TreeData = data;
      this.displayData = this.TreeData;
      this.MenuService.GetAppMenusByRoleIdId(this.data.rowItem.id).subscribe((roleData: any[]) => {
        this.selectMenus = roleData;
        this.displayData = this.TreeData.map((item: { open: boolean; isChecked: boolean; halfChecked: boolean; childrenMenu: any[]; id:any}) => {
          const checkChildren = (childrenMenu: any[]): any[] => {
            if (!childrenMenu) return [];

            let allChildrenChecked = true;
            let hasCheckedChild = false;

            const updatedChildren = childrenMenu.map(child => {
              if (this.isMenuSelected(child.id, this.selectMenus)) {
                child.isChecked = true;
                hasCheckedChild = true;
              } else {
                allChildrenChecked = false;
              }
              if (child.childrenMenu && child.childrenMenu.length > 0) {
                child.childrenMenu = checkChildren(child.childrenMenu);
                child.open = true; // 确保存在下级菜单的菜单项open为true
                if (child.childrenMenu.every(c => c.isChecked)) {
                  child.isChecked = true;
                } else if (child.childrenMenu.some(c => c.isChecked || c.halfChecked)) {
                  child.halfChecked = true;
                  hasCheckedChild = true;
                }
                if (!child.childrenMenu.every(c => c.isChecked)) {
                  allChildrenChecked = false;
                }
              }
              return child;
            });

            return updatedChildren;
          };
          if (item.childrenMenu && item.childrenMenu.length > 0) {
            item.childrenMenu = checkChildren(item.childrenMenu);

            if (item.childrenMenu.every(child => child.isChecked)) {
              item.isChecked = true;
            } else if (item.childrenMenu.some(child => child.isChecked || child.halfChecked)) {
              item.halfChecked = true;
            } else {
              item.isChecked = false;
              item.halfChecked = false;
            }
          } else {
            // 如果没有子项，确保节点的 isChecked 和 halfChecked 状态不会被错误地设置
            item.isChecked = this.isMenuSelected(item.id, this.selectMenus);
            item.halfChecked = false;
          }
          item.open = true; // 确保存在下级菜单的菜单项open为true
          return item;
        });
      });
    });
    }
    isMenuSelected(menuId: number, menus: any[]): boolean {
      for (const menu of menus) {
        if (menu.id === menuId) {
          return true;
        }
        if (menu.childrenMenu && menu.childrenMenu.length > 0) {
          if (this.isMenuSelected(menuId, menu.childrenMenu)) {
            return true;
          }
        }
      }
      return false;
    }
    nodeChecked($event: any) {
      this.selectIds = this.getTitles($event);
      console.log(this.selectIds);
      this.selectMenus = this.displayData
    .map(menu => this.selectMenusF(menu, this.selectIds))
    .filter(menu => menu !== null)
    }
    selectMenusF(menu: any, selectedIds: number[]): any {
      if (selectedIds.includes(menu.id)) {
        return {
          ...menu,
          childrenMenu: menu.childrenMenu
            ? menu.childrenMenu
                .map(child => this.selectMenusF(child, selectedIds))
                .filter(child => child !== null)
            : []
        };
      } else if (menu.childrenMenu && menu.childrenMenu.length > 0) {
        const filteredChildren = menu.childrenMenu
          .map(child => this.selectMenusF(child, selectedIds))
          .filter(child => child !== null);
        if (filteredChildren.length > 0) {
          return {
            ...menu,
            childrenMenu: filteredChildren
          };
        }
      }
      return null;
    }
    getTitles(nodes: any[]) {
      let titles = [];
      nodes.forEach(node => {
        if (node && node.data && node.data.originItem.id
        ) {
          titles.push(node.data.originItem.id);
        }
        if (node && node.childrenMenu) {
          titles = titles.concat(this.getTitles(node.childrenMenu));
        }
      });
      return titles;
    }
    searchDepartment($event: any) {
      this.searchDirctoryValue = $event.target.value;
      this.displayData = this.filterNodes(this.TreeData, this.searchDirctoryValue);
    }
    filterNodes(nodes: any[], searchTerm: string) {
      let result = [];
      for (let node of nodes) {
        // 如果节点的 title 属性包含搜索词，将整个节点添加到结果中
        if (node.title && node.title.includes(searchTerm)) {
          result.push(node);
        } else if (node.childrenMenu) {
          node.open = true;
          // 否则，如果节点有 childrenMenu 属性，递归过滤 childrenMenu
          let filteredChildren = this.filterNodes(node.childrenMenu, searchTerm);
          if (filteredChildren.length > 0) {
            // 如果有任何 childrenMenu 符合条件，创建一个新的节点，其 childrenMenu 是过滤后的结果
            let newNode = { ...node, childrenMenu: filteredChildren };
            result.push(newNode);
          }
        }
      }
      return result;
    }
}
